<!DOCTYPE html>
<!--
Copyright 2020 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta
      name="viewport"
      content="width=device-width, initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5">
    <title>Secure Payment Confirmation Debug Tool</title>
    <style>
      #output {
        font-family: monospace;
      }
    </style>
    <script>
      /**
       * Computes the SHA-256 hash of the provided payload to print on screen.
       */
      async function getHash() {
        let raw_input = document.querySelector('#json').value;
        let json_str = sanitizeInput(raw_input);
        print('#json_str', json_str);

        try {
          let bytes = Uint8Array.from(json_str, c => c.charCodeAt(0));
          print('#json_bytes', bytes.toString());

          // Hash over binary form of b64 encoding.
          let hash = await crypto.subtle.digest('SHA-256', bytes.buffer);

          // hash is an ArrayBuffer, convert it to Uint8Array.
          let array = new Uint8Array(hash);
          print('#hash_bytes', array.toString());
        } catch (e) {
          console.log(e.message);
        }

        let json = JSON.parse(json_str);
        console.log(json);
      }

      /**
       * Creates a compat serialization of the provided raw JSON representation.
       */
      function sanitizeInput(raw) {
        let json = JSON.parse(raw);
        let sanitized = JSON.stringify(json, null, 0);
        return sanitized;
      }

      /**
       * Helper function to print |value| to the DOMElement with |selector|.
       */
      function print(selector, value) {
        document.querySelector(selector).innerText = value;
      }
    </script>
  </head>
  <body>
    <h1>Secure Payment Confirmation Unit Test Helper</h1>
    <p>
      This page is a helper utility to generate new test expectations for
      //components/payments/content/secure_payment_confirmation_app_unittest.cc.
    </p>
    <p>Steps:</p>
    <ol>
      <li>Copy new payload into the text box.</li>
      <li>Click on "Get SHA-256"</li>
      <li>Copy the generated SHA-256 bytes into |expected_bytes| in secure_payment_confirmation_app_unittest.cc.</li>
    </ol>
    <hr>
    <p>Payload:</p>
    <textarea id="json" rows="20" cols="60">{
      "merchantData": {
        "merchantOrigin": "https://merchant.example",
        "total": {
          "currency": "USD",
          "value":"1.25"
        }
      }
    }</textarea>
    <p><button id="getHash" onclick="getHash()">Get SHA-256</button></p>

    <hr>
    <div id="output">
      <p>Input string: </p>
      <div id="json_str"></div>
      <p>Input bytes: </p>
      <div id="json_bytes"></div>
      <p>SHA-256 bytes: </p>
      <div id="hash_bytes"></div>
    </div>
  </body>
</html>
